package com.zelin.web.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Controller
public class UserController {

    @RequestMapping("/user/login")
    public String login(String username, String password, Model model, HttpSession session){
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        model.addAttribute("username",username);

        //判断用户名是否存在，密码是否是123
        if(StrUtil.isNotBlank(username) && "123".equals(password)){
            //将用户名放到session作用域中
            session.setAttribute("username",username);
            //跳转到欢迎页面
            return "welcome";
        }
        //如果用户名为null或密码不是123，就跳转到登录页
        return "redirect:/login.jsp";
    }

    @PostMapping("/user/upload")
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        ServletContext sc = request.getServletContext();
        //得到上传的文件名
        String filename = file.getOriginalFilename();
        // 得到后缀名
        String suffix = filename.substring(filename.indexOf("."));
        // 随机生成一个uuid作为文件名
        String name = UUID.randomUUID().toString();
        // 得到upload文件夹的真实的物理路径
        String realPath = sc.getRealPath("/upload");
        System.out.println("realPath = " + realPath);
        //得到最终要上传的文件 对象
        File dest = new File(realPath,name+suffix);
        // 进行文件上传
        file.transferTo(dest);
        //7跳转到文件列表页面
        return "fileList";
    }

    @RequestMapping("user/download")
    public ResponseEntity<byte[]> download(String fileName,HttpServletRequest request){
        // 得到ServletContext
        ServletContext sc = request.getServletContext();
        // 得到文件的完整路径
        String realPath = sc.getRealPath("/upload");
        // 得到真实的文件对象
        File dest = new File(realPath,fileName);
        // 将文件对象读取到字节数组中
        byte[] bytes = FileUtil.readBytes(dest);
        // 设置请求头，并以附件的形式打开，出现“另存为”对话框
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",fileName);   //出现“另存为”
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);           //以二进制流的形式打开
        //返回
        return new ResponseEntity<>(bytes,headers, HttpStatus.CREATED);
    }
}
